﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Input;
using GlobalizationTools.Model;
using GlobalizationTools.UI;
using Microsoft.Win32;

namespace GlobalizationTools.ViewModel
{
    public class TreeViewRootViewModel : CommandViewModel
    {
        public static RoutedUICommandEx OpenCommand = new RoutedUICommandEx(LocalizationResource.Open, "Open", typeof(TreeViewRootViewModel), "/ViewModel/Images/Open.png", Key.O, ModifierKeys.Control);
        public static RoutedUICommandEx SaveCommand = new RoutedUICommandEx(LocalizationResource.Save, "Save", typeof(TabControlItemViewModel), "/ViewModel/Images/Save.png", Key.S, ModifierKeys.Control);
        public static RoutedUICommandEx SaveAllCommand = new RoutedUICommandEx(LocalizationResource.SaveAll, "SaveAll", typeof(TabControlItemViewModel), "/ViewModel/Images/SaveAll.png", Key.S, ModifierKeys.Control | ModifierKeys.Shift);

        #region Data

        readonly ObservableCollection<TreeViewItemViewModel> _children;

        #endregion Data

        public TreeViewRootViewModel()
        {
            _children = new ObservableCollection<TreeViewItemViewModel>();
            _resources = new ObservableCollection<TabControlItemViewModel>();
            this.StatusText = LocalizationResource.Ready;
        }

        #region Functions

        public void AddSolutionOrProject(string path)
        {
            bool supported = true;
            try
            {
                Mouse.OverrideCursor = Cursors.Wait;
                this.StatusText = LocalizationResource.Loading;
                string extension = Path.GetExtension(path).ToLower();
                if (extension == ".sln")
                {
                    Solution solution = new Solution(path);
                    _children.Add(new TreeViewSolutionViewModel(this, solution));
                }
                else if (extension.EndsWith("proj"))
                {
                    Project project = new Project(path);
                    _children.Add(new TreeViewProjectViewModel(this, project));
                }
                else if (extension == ".resx")
                {
                    LoadResource(path);
                }
                else
                {
                    supported = false;
                }
            }
            finally
            {
                this.StatusText = LocalizationResource.Ready;
                Mouse.OverrideCursor = null;
            }

            if (!supported)
                MessageBox.Show(LocalizationResource.ExtensionNotSupported, LocalizationResource.Error, MessageBoxButton.OK, MessageBoxImage.Error);
        }

        private void LoadResource(string path)
        {
            Resource resource = new Resource(path, true);
            string[] files = Directory.GetFiles(Path.GetDirectoryName(path),
                string.Concat(Path.GetFileNameWithoutExtension(path), ".*", Path.GetExtension(path)), SearchOption.TopDirectoryOnly);
            TreeViewResourceViewModel rootResource = new TreeViewResourceViewModel(this, resource, files.Length > 0);
            _children.Add(rootResource);
            foreach (string file in files)
            {
                resource = new Resource(file, false);
                rootResource.Children.Add(new TreeViewResourceViewModel(rootResource, resource));
            }
        }

        public override void AddCommandModels(List<CommandBinding> List)
        {
            List.Add(new CommandBinding(OpenCommand, new ExecutedRoutedEventHandler(ExecuteOpen)));
            List.Add(new CommandBinding(SaveCommand, new ExecutedRoutedEventHandler(ExecuteSave), new CanExecuteRoutedEventHandler(CanExecuteSave)));
            List.Add(new CommandBinding(SaveAllCommand, new ExecutedRoutedEventHandler(ExecuteSaveAll), new CanExecuteRoutedEventHandler(CanExecuteSaveAll)));
            List.Add(new CommandBinding(ApplicationCommands.Close, new ExecutedRoutedEventHandler(ExecuteClose)));
        }

        public override void AddInputModels(List<InputBinding> List)
        {
        }

        #endregion Functions

        #region Properties

        /// <summary>
        /// Returns the logical child items of this object.
        /// </summary>
        public ObservableCollection<TreeViewItemViewModel> Children
        {
            get { return _children; }
        }

        #endregion Properties

        static OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = LocalizationResource.OpenFilter };

        private void ExecuteOpen(object sender, ExecutedRoutedEventArgs e)
        {
            FrameworkElement control = (FrameworkElement)sender;
            Window window = UIHelper.FindParent<Window>(control);
            if (openFileDialog.ShowDialog(window) ?? false)
            {
                this.AddSolutionOrProject(openFileDialog.FileName);
            }
        }

        private void ExecuteSave(object sender, ExecutedRoutedEventArgs e)
        {
            if (_selectedTabControlModel != null && _selectedTabControlModel.IsModified)
            {
                _selectedTabControlModel.Save();
            }
        }

        private void CanExecuteSave(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _selectedTabControlModel != null && _selectedTabControlModel.IsModified;
            e.Handled = true;
        }

        private void ExecuteSaveAll(object sender, ExecutedRoutedEventArgs e)
        {
            foreach (TabControlItemViewModel model in _resources)
            {
                if (model.IsModified)
                {
                    model.Save();
                }
            }
        }

        private void CanExecuteSaveAll(object sender, CanExecuteRoutedEventArgs e)
        {
            bool result = false;
            foreach (TabControlItemViewModel model in _resources)
            {
                if (model.IsModified)
                {
                    result = true;
                    break;
                }
            }
            e.CanExecute = result;
            e.Handled = true;
        }

        private void ExecuteClose(object sender, ExecutedRoutedEventArgs e)
        {
            UIHelper.FindParent<Window>((DependencyObject)sender).Close();
        }


        #region Data

        readonly ObservableCollection<TabControlItemViewModel> _resources;
        TabControlItemViewModel _selectedTabControlModel = null;

        public TabControlItemViewModel SelectedTabControlModel
        {
            get { return _selectedTabControlModel; }
            set
            {
                if (_selectedTabControlModel != value)
                {
                    _selectedTabControlModel = value;
                    OnPropertyChanged("SelectedTabControlModel");
                }
            }
        }

        #endregion Data

        #region Properties

        /// <summary>
        /// Returns the logical child items of this object.
        /// </summary>
        public ObservableCollection<TabControlItemViewModel> Resources
        {
            get { return _resources; }
        }

        #endregion Properties


    }
}
